package com.zyw.zhuangdian.service.impl;

import com.zyw.zhuangdian.constant.ServiceConstant;
import com.zyw.zhuangdian.dao.ArticleDao;
import com.zyw.zhuangdian.pojo.Resp;
import com.zyw.zhuangdian.pojo.dto.PageDto;
import com.zyw.zhuangdian.pojo.in.ArticleDtoIn;
import com.zyw.zhuangdian.pojo.out.ArticleDtoOut;
import com.zyw.zhuangdian.pojo.out.UserDtoOut;
import com.zyw.zhuangdian.property.MyProperties;
import com.zyw.zhuangdian.service.ArticleService;
import com.zyw.zhuangdian.util.BeanConvertUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {
    private final Logger logger = LoggerFactory.getLogger(ArticleServiceImpl.class);

    @Autowired
    private ArticleDao ArticleDao;

    @Autowired
    private MyProperties properties;

    @Override
    public Resp<Void> addArticle(ArticleDtoIn in) {
        Resp<Void> resp = new Resp<>();

        ArticleDao.addArticle(BeanConvertUtil.beanCovertMap(in));
        return resp;
    }

    @Override
    public Resp<Void> updateArticle(ArticleDtoIn in) {
        Resp<Void> resp = new Resp<>();

        ArticleDao.updateArticle(BeanConvertUtil.beanCovertMap(in));
        return resp;
    }

    @Override
    public Resp<Void> deleteArticle(ArticleDtoIn in) {
        Resp<Void> resp = new Resp<>();

        in.setStatus(ServiceConstant.STATUS_INVALID);

        ArticleDao.updateArticle(BeanConvertUtil.beanCovertMap(in));
        return resp;
    }

    @Override
    public Resp<List<ArticleDtoOut>> listArticles(ArticleDtoIn in) {
        Resp<List<ArticleDtoOut>> resp = new Resp<>();
        if (in.getPage() != PageDto.DEFAULT_PAGE){
            if (in.getRow() == PageDto.DEFAULT_PAGE){
                in.setPage(PageDto.DEFAULT_PAGE);
            }else{
                in.setPage((in.getPage() - 1) * in.getRow());
            }
        }
        int count = ArticleDao.listArticlesCount(BeanConvertUtil.beanCovertMap(in));
        if (count > 0){
            List<Map> articles = ArticleDao.listArticles(BeanConvertUtil.beanCovertMap(in));
            List<ArticleDtoOut> dtoOuts = new ArrayList<>();
            for (Map m: articles){
                ArticleDtoOut o = BeanConvertUtil.covertBean(m,ArticleDtoOut.class);
                o.setPublisherUser(BeanConvertUtil.covertBean(m,UserDtoOut.class));
                o.getPublisherUser().harmless();
                dtoOuts.add(o);
            }
            resp.setData(dtoOuts);
        }

        resp.setTotal(count);
        if (in.getPage() != PageDto.DEFAULT_PAGE) {
            resp.setRecords((int) Math.ceil((double) count / (double) in.getRow()));
            resp.setPage(in.getPage());
            resp.setRow(in.getRow());
        }
        return resp;
    }
}
